<template>
  <view class="refund-page">
    <view class="form-scroll">
      <view class="form-container">
        <!-- 退费金额输入框（只提示不自动赋值） -->
        <view class="form-item">
          <view class="label">退费金额</view>
          <view class="input-wrapper">
            <text class="money-symbol">¥</text>
            <!-- <input
              type="number"
              step="0.01"
              placeholder="请输入退费金额"
              v-model="refundAmount"
              class="amount-input"
              @input="handleAmountInput" /> -->
            <input
              type="text"
              inputmode="decimal"
              placeholder="请输入退费金额"
              v-model="refundAmount"
              class="amount-input"
              @input="handleAmountInput" />

            <text class="max-amount">
              最高可退: ¥{{ orderAmount.toFixed(2) }}
            </text>
          </view>
        </view>

        <!-- 退费原因文本框 -->
        <view class="form-item reason-item">
          <view class="label">退费原因</view>
          <textarea
            placeholder="请详细描述退费原因（最多500字）"
            v-model="refundReason"
            class="reason-textarea"
            maxlength="500"
            auto-height />
          <view class="word-count">{{ refundReason.length }}/500</view>
        </view>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-btn-container">
      <view class="submit-btn" @click="handleSubmit">提交申请</view>
    </view>
  </view>
</template>

<script>
import * as orderInfo from "../../common/api/orderInfo.js";
export default {
  data() {
    return {
      refundAmount: "", // 退费金额（输入绑定用）
      refundReason: "", // 退费原因
      uid: "", // 订单ID
      orderAmount: 0, // 订单总金额（数字类型）
    };
  },
  onLoad(data) {
    this.uid = data.uid;
    // 转换订单金额为数字（保留两位小数，处理精度）
    this.orderAmount = Math.max(
      0,
      Math.round((parseFloat(data.orderAmount) || 0) * 100) / 100
    );
  },
  methods: {
    // 处理金额输入（只提示不自动赋值）
    handleAmountInput() {
      if (!this.refundAmount) return;

      // 1. 清除非法字符，保留数字和小数点
      this.refundAmount = this.refundAmount
        .replace(/[^\d.]/g, "") // 只保留数字和小数点
        .replace(/\.{2,}/g, ".") // 限制一个小数点
        .replace(/^0+(\d)/, "$1") // 去除前置多余的0（如"00123"→"123"）
        .replace(/^(\d+)\.(\d{2}).*$/, "$1.$2"); // 小数点后最多两位

      // 2. 处理以小数点开头的情况（如".12"→"0.12"）
      if (this.refundAmount.startsWith(".")) {
        this.refundAmount = "0" + this.refundAmount;
      }

      // 3. 实时校验：超过最大金额时只提示，不修改输入值
      const refundNum = parseFloat(this.refundAmount) || 0;
      const refundFixed = Math.round(refundNum * 100) / 100; // 处理精度
      const orderFixed = this.orderAmount;

      if (refundFixed > orderFixed) {
        // 只显示提示，不修改输入框的值
        uni.showToast({
          title: `退费金额不能超过¥${orderFixed.toFixed(2)}`,
          icon: "none",
          duration: 1500,
        });
      }
    },

    // 表单验证（提交时严格校验金额）
    validateForm() {
      // 验证订单金额有效性
      if (this.orderAmount <= 0) {
        uni.showToast({ title: "订单金额异常", icon: "none" });
        return false;
      }

      // 验证退费金额
      if (!this.refundAmount) {
        uni.showToast({ title: "请输入退费金额", icon: "none" });
        return false;
      }
      const refundNum = parseFloat(this.refundAmount);
      const refundFixed = Math.round(refundNum * 100) / 100;
      if (refundFixed <= 0) {
        uni.showToast({ title: "退费金额必须大于0", icon: "none" });
        return false;
      }
      // 提交时再次校验是否超过最大金额
      if (refundFixed > this.orderAmount) {
        uni.showToast({
          title: `退费金额不能超过¥${this.orderAmount.toFixed(2)}`,
          icon: "none",
        });
        return false;
      }

      // 验证退费原因
      if (!this.refundReason.trim()) {
        uni.showToast({ title: "请输入退费原因", icon: "none" });
        return false;
      }
      if (this.refundReason.length < 5) {
        uni.showToast({ title: "退费原因请至少输入5个字", icon: "none" });
        return false;
      }

      return true;
    },

    // 提交申请
    handleSubmit() {
      if (!this.validateForm()) return;

      const submitData = {
        uid: this.uid,
        refundAmount: parseFloat(this.refundAmount),
        refundFlag: this.refundReason,
        status: "待退款",
        refundTime: new Date(),
      };

      console.log("提交退费申请：", submitData);
      orderInfo
        .update(submitData)
        .then((result) => {
          uni.showToast({ title: "申请提交成功", icon: "success" });
          setTimeout(() => uni.navigateBack(), 1500);
          // uni.navigateTo({
          //   url: "/pages/index/index",
          // });
        })
        .catch((error) => {
          console.error("提交失败：", error);
          uni.showToast({ title: "提交失败，请重试", icon: "none" });
        });
    },
  },
};
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
.refund-page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 30rpx;
  box-sizing: border-box;
}

.form-scroll {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 30rpx;
}

.form-container {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
}

.form-item {
  margin-bottom: 40rpx;
}

.reason-item {
  margin-bottom: 60rpx;
}

.label {
  font-size: 30rpx;
  color: #666;
  margin-bottom: 15rpx;
  display: block;
}

.input-wrapper {
  display: flex;
  align-items: center;
  border: 2rpx solid #eee;
  border-radius: 10rpx;
  padding: 20rpx;
}

.money-symbol {
  color: #333;
  font-size: 30rpx;
  margin-right: 10rpx;
}

.amount-input {
  flex: 1;
  font-size: 30rpx;
  color: #333;
  height: 40rpx;
}

.max-amount {
  font-size: 26rpx;
  color: #999;
  margin-left: 15rpx;
  white-space: nowrap;
}

.reason-textarea {
  width: 100%;
  border: 2rpx solid #eee;
  border-radius: 10rpx;
  padding: 20rpx;
  font-size: 30rpx;
  color: #333;
  min-height: 300rpx;
  box-sizing: border-box;
  line-height: 1.6;
}

.word-count {
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.submit-btn-container {
  width: 100%;
  padding: 30rpx 0;
  background-color: #f5f5f5;
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  background-color: #2eb0d9;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  letter-spacing: 2rpx;
  box-shadow: 0 4rpx 10rpx rgba(46, 176, 217, 0.3);
}
</style>
